//
//  CalculateDepth.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/17.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
enum CompareStates {
    case larget
    case same
    case small
}

class CalculateDepth: NSObject, DepthSortDelegate {
    

    func sortDepthData(model: DepthModel,digit:Int) {
       
        self.exchangeDepth(digit: digit, model: model)
        
    }
    
    
    /// 整理上下游数据
    ///
    /// - Parameters:
    ///   - digit: 小数位数
    ///   - model: 数据源
    func exchangeDepth(digit:Int, model:DepthModel) {
        
        let upstreamArr = model.metadata["a"]
        let downstreamArr = model.metadata["b"]
        
        if !(upstreamArr is NSNull) {
            if ((upstreamArr as? Array<Any>) != nil) {
                self.calculate(dataArr: upstreamArr as! Array<Any>, pattern: true,digit: digit, model: model)
            }else {
                model.depUpArr = []
            }
        }else {
            model.depUpArr = []
        }
        if !(downstreamArr is NSNull) {
            if ((downstreamArr as? Array<Any>) != nil) {
                self.calculate(dataArr: downstreamArr as! Array<Any>, pattern: false,digit: digit, model: model)
            }else {
                model.deptDownArr = []
            }
        }else {
            model.deptDownArr = []
        }

    }
    
    
    /// 分别整理上下游数据 存入model
    ///
    /// - Parameters:
    ///   - dataArr: 上下游数据源
    ///   - pattern: 标记上下游
    ///   - digit: 小数位数
    ///   - model: 数据源
    func calculate(dataArr:Array<Any>, pattern:Bool, digit:Int, model:DepthModel) {
        var depthUpArr:Array<DepdetailModel> = Array()
        for (_,c) in (dataArr as NSArray).enumerated() {
            let data:Array = Array(c as! NSArray)
            if data.count < 2 {
                continue
            }
            let firstString = self.changeNumber(data: (data.first as! Double), digit: digit, pattern: pattern)
            let smallModel = DepdetailModel(number:String(format: "%@",
                                                          data.last as! CVarArg),price:firstString,digit:digit)
            self.changeNumber(model: smallModel,pattern:pattern)
            depthUpArr.append(smallModel)
            
        }
        
//        if digit == 6 {
//            if pattern {
//              depthUpArr =  depthUpArr.reversed()
//            }
//
//        }else {
//        for i in 0..<depthUpArr.count {
//            for j in 0..<depthUpArr.count - (i+1) {
//                let depthModel = depthUpArr[j]
//                let nextDepthModel = depthUpArr[j+1]
//                let states = self.campare(currentModel: depthModel, lastModel: nextDepthModel)
//                if states == .small {
//                    let temp = depthUpArr[j]
//                    depthUpArr[j] = depthUpArr[j+1]
//                    depthUpArr[j+1] = temp
//                }
//
//            }
//         }
//        }
        if pattern {
            depthUpArr =  depthUpArr.reversed()
        }
        var deleNumber = 0
        for i in 0..<depthUpArr.count {
            if i + 1  > depthUpArr.count {
                break
            }
            let topModel = depthUpArr[i]
            deleNumber = 0
            for j in i+1..<depthUpArr.count  {
                let depthModel = depthUpArr[j-deleNumber]
                let states = self.campare(currentModel: topModel, lastModel: depthModel)
                
                if states == .same {
                    self.addNumber(model: topModel, laseModel: depthModel)
                    depthUpArr.remove(at: j-deleNumber)
                    deleNumber = deleNumber + 1
                }
            }
        }
        
        //问题出现在这里 取的是下游5档
        if pattern {
            if depthUpArr.count > 5 {
                depthUpArr.removeSubrange(Range(0..<depthUpArr.count-5))
            }
        }else {
            if depthUpArr.count > 5 {
                depthUpArr.removeSubrange(Range(5..<depthUpArr.count))
            }
    
        }

        self.archiveBigNumber(depthUpArr: depthUpArr, pattern: pattern, depModel: model)
        
        //问题出现在这里 取的是下游5档
        if pattern {
            model.depUpArr = depthUpArr
        }else {
            model.deptDownArr = depthUpArr
        }
    }
    

    
    /// 比较数据price的大小
    ///
    /// - Parameters:
    ///   - currentModel: 数据源
    ///   - lastModel: 数据源
    /// - Returns: 枚举
    func campare(currentModel:DepdetailModel,lastModel:DepdetailModel) -> CompareStates{
        let currentNumber = CalculateDepth.decimalNumber(num: Double(currentModel.price)!)
        let lastNumber = CalculateDepth.decimalNumber(num: Double(lastModel.price)!)
        let resulet = currentNumber.compare(lastNumber)
        if resulet == .orderedAscending {
            return .small
        }else if resulet == .orderedSame {
            return .same
        }else {
           return .larget
        }
    }
    
    
    
    /// 切换小数
    ///
    /// - Parameters:
    ///   - data: 数据源
    ///   - digit: 小数位数
    /// - Returns: 回调
    func changeNumber(data:Double,digit:Int,pattern:Bool) -> String {
      
        let roundUp = NSDecimalNumberHandler(roundingMode: pattern ? NSDecimalNumber.RoundingMode.up : NSDecimalNumber.RoundingMode.down,
                                             scale: Int16(digit),
                                             raiseOnExactness: false,
                                             raiseOnOverflow: false,
                                             raiseOnUnderflow: false,
                                             raiseOnDivideByZero: false)
        let first = CalculateDepth.decimalNumber(num: data)
        let price  = first.rounding(accordingToBehavior: roundUp)
        if digit != 0 {
        var formatterString : String = "0."
        let count : Int = (digit < 0 ? 0 : digit)
        for _ in 0 ..< count {
            formatterString.append("0")
        }
        let formatter : NumberFormatter = NumberFormatter()
        //      设置生成好的格式，NSNumberFormatter 对象会按精确度自动四舍五入
        formatter.positiveFormat = formatterString
        //          然后把这个number 对象格式化成我们需要的格式，
        //          最后以string 类型返回结果。
        return formatter.string(from: price)!
        }else {
            return price.description.count != 0 ? price.description : "0"
        }
    }
    
    
    /// 数量相加
    ///
    /// - Parameters:
    ///   - model: 数据源
    ///   - laseModel: 数据源
    func addNumber(model:DepdetailModel,laseModel:DepdetailModel) {
        let roundUp = NSDecimalNumberHandler(roundingMode: NSDecimalNumber.RoundingMode.down,
                                             scale: 3,
                                             raiseOnExactness: false,
                                             raiseOnOverflow: false,
                                             raiseOnUnderflow: false,
                                             raiseOnDivideByZero: false)
        let first = CalculateDepth.decimalNumber(num: Double(model.number)!)
        let last = CalculateDepth.decimalNumber(num: Double(laseModel.number)!)
        let price = first.adding(last, withBehavior: roundUp)
        let string = String(format: "%@", price)
        model.number =  string
    }
    
    func changeNumber(model:DepdetailModel,pattern:Bool = false) {
        
        let roundUp = NSDecimalNumberHandler(roundingMode: pattern ? NSDecimalNumber.RoundingMode.up : NSDecimalNumber.RoundingMode.down,
                                             scale: 3,
                                             raiseOnExactness: false,
                                             raiseOnOverflow: false,
                                             raiseOnUnderflow: false,
                                             raiseOnDivideByZero: false)
        let first = CalculateDepth.decimalNumber(num: Double(model.number)!)
        let price  = first.rounding(accordingToBehavior: roundUp)
        let string = String(format: "%@", price)
        model.number = string
        
    }
    
    
    
    /// 获取上下游5档位最大值
    ///
    /// - Parameters:
    ///   - depthUpArr: 数据源
    ///   - pattern: 标记上游 下游
    ///   - depModel: model
    func archiveBigNumber(depthUpArr:Array<DepdetailModel> , pattern:Bool,depModel:DepthModel) {
        if pattern {
            depModel.depthBigNumber = "0"
        }
        (depthUpArr as NSArray).enumerateObjects { (model, index, stop) in
            let model = model as! DepdetailModel
            if index > 4 {
                stop.initialize(to: true)
            }
            let currentNumber = CalculateDepth.decimalNumber(num: Double(depModel.depthBigNumber)!)
            let lastNumber = CalculateDepth.decimalNumber(num: Double(model.number)!)
            let resulet = currentNumber.compare(lastNumber)
            if resulet == .orderedAscending  {
                depModel.depthBigNumber = model.number
            }
        }
    }
    
    class func decimalNumber(num:Double) -> NSDecimalNumber {
        let roundUp = NSDecimalNumberHandler(roundingMode: NSDecimalNumber.RoundingMode.bankers,
                                             scale: 10,
                                             raiseOnExactness: false,
                                             raiseOnOverflow: false,
                                             raiseOnUnderflow: false,
                                             raiseOnDivideByZero: false)
        return NSDecimalNumber(value: num).rounding(accordingToBehavior: roundUp)
    }
    
    
}
